﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Optimization;
using System.Xml.Serialization;
using JuCheap.Template.Web.Models;

namespace JuCheap.Template.Web
{
    /// <summary>
    /// BundleConfig
    /// </summary>
    public class BundleConfig
    {
        // 有关绑定的详细信息，请访问 http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            //重新处理bundle忽略资源的规则
            bundles.IgnoreList.Clear();
            AddDefaultIgnorePatterns(bundles.IgnoreList);

            var fileList = getFiles();

            fileList.ForEach(f =>
            {
                string type = f.Type.Trim().ToLower(), virtualUrl = f.VirtualUrl.Trim().ToLower();
                if (type.Equals("js"))
                {
                    bundles.Add(new ScriptBundle(virtualUrl).Include(f.Srcs.ToArray()));
                }
                else if (type.Equals("css"))
                {
                    bundles.Add(new StyleBundle(virtualUrl).Include(f.Srcs.ToArray()));
                }
            });
        }

        /// <summary>
        /// 压缩静态文件，需要忽略的文件命名规则
        /// </summary>
        /// <param name="ignoreList"></param>
        static void AddDefaultIgnorePatterns(IgnoreList ignoreList)
        {
            if (ignoreList == null)
                throw new ArgumentNullException("ignoreList");

            ignoreList.Ignore("*.intellisense.js");
            ignoreList.Ignore("*-vsdoc.js");
            ignoreList.Ignore("*.debug.js", OptimizationMode.WhenEnabled);
            //ignoreList.Ignore("*.min.js", OptimizationMode.WhenDisabled);
            //ignoreList.Ignore("*.min.css", OptimizationMode.WhenDisabled);
        }

        /// <summary>
        /// 获取所有的静态文件配置信息
        /// </summary>
        /// <returns></returns>
        static List<StaticFileModel> getFiles()
        {
            var filePath = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "/Config/Flat.config");
            return DeserializeFromXml<List<StaticFileModel>>(filePath);
        }

        /// <summary>
        /// 从某一XML文件反序列化到某一类型
        /// </summary>
        /// <param name="filePath">待反序列化的XML文件名称</param>
        /// <returns></returns>
        static T DeserializeFromXml<T>(string filePath)
        {
            try
            {
                if (!File.Exists(filePath))
                    throw new FileNotFoundException();

                using (StreamReader reader = new StreamReader(filePath))
                {
                    var xs = new XmlSerializer(typeof(T));
                    T ret = (T)xs.Deserialize(reader);
                    return ret;
                }
            }
            catch
            {
                return default(T);
            }
        }
    }
}
